package com.springcloud.controller;

import com.springcloud.common.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: 顾志杰
 */
@RestController
@Slf4j
@RequestMapping("gateway")
public class GatewayController {

    public static final Map<Long, Product> ITEMS = new ConcurrentHashMap<>();


    /**
     * 发布商品
     * @param pid
     * @return
     */
    @RequestMapping(value = "details", method = RequestMethod.GET)
    @ResponseBody
    public Product get(@RequestParam("pid") Long pid) {
        /*如果不存在就创建一个product*/
        if (!ITEMS.containsKey(pid)) {
            Product prod = Product.builder()
                    .productId(pid)
                    .description("好吃不贵")
                    .stock(100L)
                    .build();
            /*如果不存在才put*/
            ITEMS.putIfAbsent(pid,prod);
        }
        return ITEMS.get(pid);
    }


    /**
     * 下单
     */
    @RequestMapping(value = "placeOrder", method = RequestMethod.GET)
    public String buy(@RequestParam("pid") Long pid){
        Product product = ITEMS.get(pid);

        if(product == null){
            return "Product not found";
        }else if(product.getStock() <= 0L){
            return "Sold out";
        }

        synchronized (product){
            if(product.getStock() <= 0L){
                return "Sold out";
            }

            product.setStock(product.getStock()-1);
        }
        return "Order Placed";
    }
}
